package com.mrzhang.glpt.server.system.common.config;

import com.mrzhang.common.handler.GlptAccessDeniedHandler;
import com.mrzhang.common.handler.GlptAuthExceptionEntryPoint;
import com.mrzhang.glpt.server.system.common.properties.GlptServerSystemProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

/**
 * 所有访问febs-server-system的请求都需要认证，只有通过认证服务器发放的令牌才能进行访问
 */
@Configuration
@EnableResourceServer
public class GlptServerSystemResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Autowired
    private GlptAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private GlptAuthExceptionEntryPoint exceptionEntryPoint;

    @Autowired
    private GlptServerSystemProperties properties;

    @Bean
    public PasswordEncoder passwordEncoder() {

        return new BCryptPasswordEncoder();
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        String[] anonUrls = StringUtils.splitByWholeSeparatorPreserveAllTokens(properties.getAnonUrl(), ",");

        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(anonUrls).permitAll()
                .antMatchers("/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}
